<template>
    <MainLayout :title="pageTitle" :breadcrumbItems="breadcrumbItems">
        <template #sidebar>
            <SideNav :items="navConfig" :active="currentNav.type" @select="handleSelect" />
        </template>

        <template #content>
            <MemberSubmission v-if="currentNav.type === 'contribute'" :contents="dataContent" prevtype="about" :type="currentNav.type">
            </MemberSubmission>
            <template v-if="currentNav.type === 'community'">
                <template v-if="filterOptions.length">
                    <Filter :filters="filterOptions" @filter-change="getFilters" />
                </template>
                <div v-if="pending" class="loading">数据加载中...</div>
                <template v-else>
                    <template v-if="communityItems.length">
                        <ContentList :items="communityItems" prevtype="members" :type="currentNav.type" />
                        <Pagination :current-page="currentPage" :total-pages="totalPages"
                            :base-url="`/members/${currentNav.type}`" />
                    </template>
                    <div v-else class="empty">暂无数据</div>
                </template>
            </template>
        </template>
    </MainLayout>
</template>

<script setup>
import MainLayout from '@/components/ListPage.vue'
import SideNav from '@/components/list/SideNav.vue'
import ContentList from '@/components/list/ContentList.vue'
import Pagination from '@/components/list/Pagination.vue'
import MemberSubmission from '@/components/members/memberSubmission.vue'
import Filter from '@/components/members/filter.vue'

const { $fetchGov, $fetchAuth } = useNuxtApp()

const localePath = useLocalePath()
//当前频道id
const currentChannelId = ref('')

const route = useRoute()
const router = useRouter()
const totalPages = ref(1)
const pending = ref(true)
const currentPage = ref(1)
const communityItems = ref([])
const dataContent = ref({})
const filterOptions = ref([]) // 过滤器选项
const selectedFilterArr = ref([])
// 获取频道列表数据
const { data: members } = await useAsyncData(
    `members-channel`,
    () => $fetchGov('/app/api/channel/alias/members', {
        method: 'GET',
        params: { isArticle: false, isTree: false,_t: Date.now() },
    })
)

// 导航配置
const navConfig = computed(() => {
    return (members.value?.data?.children || []).map(item => ({
        // 添加错误处理
        type: item.routerPath,
        title: item.name,
        id: item.id,
        path: `/members/${item.routerPath}`
    }))
})

const getFilters = async (selectedFilters) => {
    selectedFilterArr.value = selectedFilters || [];
};

// 定义一个数组来存储选中的筛选条件
const debounce = (fn, delay) => {
    let timeoutId;
    return (...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn.apply(this, args), delay);
    };
};

const fetchFilters = async () => {
    try {
        const { data } = await $fetchGov('/app/api/channel/filtrate', {
            params: { id: currentChannelId.value,_t: Date.now()}
        })
        filterOptions.value = data?.map(item => ({
            ...item,
            currentFilter: item.dictList[0]?.id,
            currentValue: ''
        })) || []
    } catch (error) {
        console.error('获取筛选项失败:', error)
        filterOptions.value = []
    }
}

// 第二步：初始化防抖控制器
let abortController = null
const fetchArticles = debounce(async () => {
    pending.value = true
    try {
        if (abortController) abortController.abort()
        abortController = new AbortController()

        // 构建动态参数
        const params = {
            channelId: currentChannelId.value,
            _t: Date.now()
        }
        if (currentNav.value.type === 'community') {
            params.page = currentPage.value
            params.pageSize = 9
        }
        if (currentNav.value.type == 'contribute') {
            params.isText = true
        }
        // 条件添加 filterCustom
        if (currentNav.value.type === 'community' && selectedFilterArr.value.length > 0) {
            const filterParams = selectedFilterArr.value
                .map(v => `${v.name}:${v.value}`)
                .join('@')
            params.filterCustom = filterParams
        } else {
            delete params.filterCustom
        }

        const { data } = await $fetchAuth('/app/api/article/page', {
            signal: abortController.signal,
            params
        })

        if (currentNav.value.type === 'contribute') {
            dataContent.value = data?.content[0] || {}
        }
        if (currentNav.value.type === 'community') {
            communityItems.value = data?.content || []
        }
        totalPages.value = Number(data?.totalPages) || 0
    } catch (err) {
        if (err.name === 'AbortError') {
            console.log('请求被取消')
        } else {
            if (currentNav.value.type === 'contribute') {
                dataContent.value = {}
            }
            if (currentNav.value.type === 'community') {
                communityItems.value = []
            }
        }
    } finally {
        pending.value = false
    }
}, 300)

// 第三步：路由参数初始化
const initParams = async () => {
    await nextTick()
    const routeType = route.params.type
    if(!navConfig.value?.length) {
        console.error('导航配置未加载')
        return
    }
    const targetNav = navConfig.value.find(nav => nav.type === routeType)
    if(!targetNav) {
        console.error(`找不到${routeType}对应的导航项`)
        router.replace(localePath('/science/all-resource'))
        return
    }
    currentChannelId.value = targetNav?.id || ''
    currentPage.value = Number(route.query.page) || 1
}

// 第四步：统一监听变化
watch(
    () => route.params.type,
    async () => {
        await initParams()
        if (!navConfig.value.length) return
        if (currentNav.value.type === 'community') {
            await fetchFilters()
        }
        fetchArticles()
    },
    { immediate: true }
)

watch(
    () => route.query.page,
    (newPage) => {
        const pageNumber = Number(newPage) || 1
        if (!navConfig.value.length) return
        if (pageNumber !== currentPage.value) {
            currentPage.value = pageNumber
            fetchArticles()
        }
    }
)

// 单独监听筛选条件变化
watch(selectedFilterArr, (newVal) => {
    currentPage.value = 1;
    router.replace({
        path: route.path,
        query: {
            ...route.query,
            page: currentPage.value > 1 ? currentPage.value : undefined
        }
    })
    fetchArticles()
}, { deep: true })

// 获取当前导航状态
const currentNav = computed(() =>
    navConfig.value.find(nav => nav.type === route.params.type) || { title: '', type: '' }
)

const pageTitle = computed(() => {
    return members.value?.data?.name || '会员专区'
})

// 面包屑导航
const breadcrumbItems = computed(() => [
    { title: '首页', path: '/' },
    { title: '会员专区', path: '/members' },
    { title: currentNav.value?.title ?? '' }
])


// 切换导航处理
const handleSelect = async (item) => {
    router.push(
        localePath({
            path: `/members/${item.type}`
        })
    )
}
</script>

<style scoped>
/* 添加样式 */
</style>